<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');



/**
* shopfiy 导单，回传物流，退款等，王明星
*/
class Shopifydata 
{
	
	function __construct()
	{
		$this->CI =& get_instance();
        $this->db1 = $this->CI->load->database('default', TRUE);
        $this->db2 = $this->CI->load->database('amazondata', TRUE);
       $this->CI->load->library('Amazondata');
       $this->amazondata=new amazondata();
	}


    public function updateshopifywebdata()
	{
		$list = $this->db1->select('uploadImages,id')->get_where("shopify.db_shopify_productlist","isupload = 1")->result_array();
		if(count($list))
		{
			foreach($list as $key=>$rs)
			{
				//先要处理图片信息
				include_once(dirname(__FILE__)."/../../fuman/upfile/TieTuKu.class.php");	//获取外部图片库API接口
				$sdk=new TTKClient('9ed9b5d096d32d5460bef0744a11fd13e21ae960','66fdb66e6cae1f2d2d16560e3b7b2da19a10e9d4');

				
				if($rs["uploadImages"])
				{
					$uploadImages = explode("|",$rs["uploadImages"]);
					$newimageslist = "";
					foreach($uploadImages as $key=>$ImagesUrl)
					{
						$result=$sdk->uploadFromWeb('1434082',$ImagesUrl);
						$resultstr = json_decode($result,true);
						$newimageslist[] = $resultstr["linkurl"];
					}
					if(count($newimageslist))
					{
						$this->db1->update("shopify.db_shopify_productlist",array("images"=>implode("|",$newimageslist)),"id='".$rs["id"]."'");
						
					}
				}

			}
		}

		$list = $this->db1->get_where("shopify.db_shopify_productlist","isupload = 1")->result_array();
		if(count($list))
		{
			$post = "";
			$update="";
			foreach($list as $key=>$rs)
			{
				if($rs["updateData"]){
				$post[$key]["product_id"] = $rs["product_id"];
				$post[$key]["parent_id"] = $rs["parent_id"];
				$post[$key]["sku"] = $rs["sku"];
				$post[$key]["updateData"] = $rs["updateData"];
				$post[$key]["is_update"]= 1;
				$post[$key]["webname"] = $rs["webname"];
				$post[$key]["inserttime"] =time();
				$post[$key]["images"] = $rs["images"];

				$update[$key]["id"] = $rs["id"];
				$update[$key]["isupload"] =2;
				}

			}

			if(count($post))
			{
				$this->db2->insert_batch('db_magento_productlist',$post);
				$this->db1->update_batch('shopify.db_shopify_productlist',$update,"id");

			}
		}
	}

    //shopify授权说明
    //首先在复漫填写域名，然后进入授权呢，返回code等
    //然后执行 http://184y169s48.imwork.net:66/exportorder/ajaxbutton?op=shopifytoken&shopid=467&code=ae45fb8cce81d1804dbd8921f92b033d
    //shopid 为网站在复漫上面的id  code 为 返回值，然后自动完成授权，
	//获取token
	public function gettoken($shopid,$code){
		    //获取店铺，和code
		$sql = "SELECT * FROM d_shop WHERE id = $shopid;";
		$rs  = $this->db1->query($sql)->row_array();
		if(!empty($rs)){
			if($rs["amazonkey"]){
				$amazonkey = json_decode($rs["amazonkey"],true);
			}
		}
		    $shop = $amazonkey['shopifytoken'];
		    $request_headers = array(
		    	"Content-type" => "application/json", // Tell Shopify that we're expecting a response in JSON format
		    	"client_id" => "daeaac41584625af84a5707f708336f6", // Your app API key
		    	"client_secret" => "1f73927bbefec664c142fd22e118de59", // Your app credentials (secret key)
		    	"code" => $code // Grab the access key from the URL
		    );
		    // Call our Shopify function
            $shopify_response = $this->shopify_call(NULL, $shop, "/admin/oauth/access_token", $request_headers, 'POST', $request_headers);

            // Convert response into a nice and simple array
            $shopify_response = json_decode($shopify_response['response'], TRUE);
            var_export($shopify_response);
            $token = $shopify_response['access_token'];
            $amazonkey['apptoken']=$token;
            var_export($amazonkey);
            $arr_app['amazonkey']=json_encode($amazonkey);

            $this->db1->where('id',$shopid);
            $this->db1->update('d_shop',$arr_app);


	}


    //从network上获取产品信息。
    public function getnetproduct($shopid){
    	$page=0;
    	while (true) {
        $page++;
        $url = "http://network.pokemoncos.com/var/getshopify/out_shopify.php?page={$page}&shopid={$shopid}";
        echo $url;
    	$date = file_get_contents($url);
    	$data = json_decode($date,true);
    	//var_dump($data);
    	if(count($data)>0)
    	    $this->db1->insert_batch("shopify.db_shopify_productlist",$data);
        else
        	break;
        }
        return 'ok';
    }



    
    //获取产品
	public function getproduct($shopid){
		//获取全部shopify店铺
		$sql="SELECT * FROM `d_shop` WHERE `platfromname` = 'Shopify' AND `id` = '{$shopid}';";
		$arr_row = $this->db1->query($sql)->result_array();
		//判断数组是否为空
		if(!empty($arr_row)){
			foreach ($arr_row as $value) {
				if(empty($value['amazonkey']))
					continue;
				$amazonkey = json_decode($value['amazonkey'],true);
				//判断是否存在shopid
				if(isset($amazonkey['apptoken'])){
					if(isset($amazonkey['shopifytoken'])){
						//这个时候说明token什么的都是有了的
						$this->getproductlist($amazonkey['apptoken'],$amazonkey['shopifytoken'],$value['id'],$value['name']);
					}
				}
			}
		}

	}

	//googleshipping 产品
	public function googleshipping($shopid){
				//获取全部shopify店铺
		$sql="SELECT * FROM `d_shop` WHERE `platfromname` = 'Shopify' AND `id` = '{$shopid}';";
		$arr_row = $this->db1->query($sql)->result_array();
		//判断数组是否为空
		if(!empty($arr_row)){
			foreach ($arr_row as $value) {
						//这个时候说明token什么的都是有了的
						$this->getgoogleshipping($value['name']);			
			}
		}
	}

	//导出Google文件
	public function getgoogleshipping($webname){
		ini_set('max_execution_time', 0);
		//已知店铺名称，根据店铺名称得出店铺产品
		$sql = "SELECT *,COUNT(DISTINCT `parent_id`) FROM `db_magento_productlist` WHERE  `webname` = '{$webname}' GROUP BY `parent_id`;";
		$res = $this->db1->query($sql)->result_array();
		//判断是否为空
		if(!empty($res)){
			$doc=new DOMDocument("1.0","utf8");
			$doc->formatOutput=true;
			//创立根节点
			$root=$doc->createElement("rss");
			$root->setAttribute("version","2.0"); 
			$root->setAttribute("xmlns:g","http://base.google.com/ns/1.0");
			$doc->appendchild($root);
			$channel=$doc->createElement("channel");
			$root->appendchild($channel);
			$title=$doc->createElement("title");
			$titleTextNode=$doc->createTextNode("Full data feed");
			$title->appendchild($titleTextNode);
			$channel->appendchild($title);
			$link=$doc->createElement("link");
			$linkTextNode=$doc->createTextNode("{$webname}");
			$link->appendchild($linkTextNode);
			$channel->appendchild($link);
			$description=$doc->createElement("description");
			$descriptionTextNode=$doc->createTextNode("This is the main feed for your online product data for Google Shopping and should be submitted at least every 30 days.");
			$description->appendchild($descriptionTextNode);
			$channel->appendchild($description);
			foreach ($res as $value) {
				    $sku = $value['sku'];
				    if(strpos($sku, '-') === false){

				    }else{
				    	$pos=strpos($sku, '-');
				    	$sku=substr($sku, 0,$pos);
				    }
		       		$item=$doc->createElement("item");
					$gid=$doc->createElement("g:id");
					$gidTextNode=$doc->createTextNode("{$sku}");
					$gid->appendchild($gidTextNode);
					$item->appendchild($gid);
					$ptitle=$doc->createElement("title");
					$ptitleTextNode=$doc->createTextNode("{$value['name']}");
					$ptitle->appendchild($ptitleTextNode);
					$item->appendchild($ptitle);
					$plike=$doc->createElement("link");
					$plikeTextNode=$doc->createTextNode("{$value['product_url']}");
					$plike->appendchild($plikeTextNode);
					$item->appendchild($plike);
					$pdescription=$doc->createElement("description");
					$pdescriptionTextNode=$doc->createTextNode("{$value['description']}");
					$pdescription->appendchild($pdescriptionTextNode);
					$item->appendchild($pdescription);
					// $ptype=$doc->createElement("g:product_type");
					// $ptypeTextNode=$doc->createTextNode("Men");
					// $ptype->appendchild($ptypeTextNode);
					// $item->appendchild($ptype);
					$pimglike=$doc->createElement("g:image_link");
					$pimglikeTextNode=$doc->createTextNode("{$value['base_image']}");
					$pimglike->appendchild($pimglikeTextNode);
					$item->appendchild($pimglike);
					$addimglike=$doc->createElement("g:additional_image_link");
					$addimglikeTextNode=$doc->createTextNode("{$value['base_image']}");
					$addimglike->appendchild($addimglikeTextNode);
					$item->appendchild($addimglike);
					$condition=$doc->createElement("g:condition");
					$conditionTextNode=$doc->createTextNode("New");
					$condition->appendchild($conditionTextNode);
					$item->appendchild($condition);
					$availability=$doc->createElement("g:availability");
					$availabilityTextNode=$doc->createTextNode("in stock");
					$availability->appendchild($availabilityTextNode);
					$item->appendchild($availability);
					$price=$doc->createElement("g:price");
					$priceTextNode=$doc->createTextNode("{$value['price']} {$value['currency']}");
					$price->appendchild($priceTextNode);
					$item->appendchild($price);
					$brand=$doc->createElement("g:brand");
					$brandTextNode=$doc->createTextNode("{$webname}");
					$brand->appendchild($brandTextNode);
					$item->appendchild($brand);
					$mpn=$doc->createElement("g:mpn");
					$mpnTextNode=$doc->createTextNode("{$sku}");
					$mpn->appendchild($mpnTextNode);
					$item->appendchild($mpn);
					$identifier_exists=$doc->createElement("g:identifier_exists");
					$identifier_existsTextNode=$doc->createTextNode("TRUE");
					$identifier_exists->appendchild($identifier_existsTextNode);
					$item->appendchild($identifier_exists);
					$shipping_weight=$doc->createElement("g:shipping_weight");
					$shipping_weightTextNode=$doc->createTextNode("{$value['weight']}kg");
					$shipping_weight->appendchild($shipping_weightTextNode);
					$item->appendchild($shipping_weight);
					$channel->appendchild($item);
			}

			//准备把文件存储到upload文件夹下面，创建shopifyGoogle文件夹，店铺名称文件夹，创建文件
			if(!file_exists("uploads/shopifygoogle")){
		         //如果不存在文件夹，则创建文件夹
		         mkdir("uploads/shopifygoogle");	
             }
             if (!file_exists("uploads/shopifygoogle/{$webname}")) {
	             mkdir("uploads/shopifygoogle/{$webname}");
             }

             $doc->save("uploads/shopifygoogle/{$webname}/googleshipping.xml");//保存文件
		}
	}

	//获取简易产品列表
	public function getproductlist($token,$shop,$shopid,$webname){
		ini_set('max_execution_time', 0);
		// 获取这个店铺的所有基础信息 GET /admin/shop.json
		$shoprs = $this-> shopify_call($token, $shop, "/admin/shop.json");
        $shoparr = json_decode($shoprs['response'],true);
        // var_dump($shoparr);
		//  /admin/product_listings.json GET
		$page=0;
		while (true) {
			$page++;
			$opt=array(
			'limit'=>200,
			'page'=>$page,
			);
			if($page >= 30 ) break;
		 //var_dump($opt);
		 $products = $this-> shopify_call($token, $shop, "/admin/products.json", $opt, 'GET');
		 $productlist=json_decode($products['response'],true);
		   var_dump($productlist);
		  // break;
		 // continue;
		 //var_dump(count($productlist['products']));
		 if(count($productlist['products']) == 0)
		 	break;
		 //把产品数据导入到数据库中
		 foreach ($productlist['products'] as $value) {
		 	//查看是否有变体
		 	//var_dump($value);
		 	//exit;
		 	$vn = count($value['variants']);
		 	$in = count($value['images']);
		 	//说明有多张图
		 	$img='';
		 	if($in > 0 ){
              foreach ($value['images'] as  $va) {
              	 $img .= $va['src'].'|'; 
              }
		 	}
		 	$imgsrc = '';
		 	if(isset($value["image"]["src"])){
               $imgsrc = $value["image"]["src"];
		 	}
		 	

		 	//说明有变体
		 	if($vn>0){
					$data=array();
               foreach ($value['variants'] as $key=>$v) {
               
               	$product_id = $v['id'];

              	//$checksql="SELECT id FROM `shopify.db_magento_productlist` WHERE `webname`='{$webname}' AND `product_id` = '{$product_id}';";
				$chrow = $this->db1->get_where('shopify.db_magento_productlist',"`webname`='{$webname}' AND `product_id` = '{$product_id}'")->result_array();
				var_dump($chrow);
				if(!$chrow){

					$data[$key]['product_id']=$product_id;
					$data[$key]['parent_id'] = $v['product_id'];
					$data[$key]['webname'] = $webname;
					$data[$key]['product_url'] = 'https://'.$shoparr['shop']['domain'].'/products/'.$value['handle'];
					$data[$key]['name'] = addslashes($value["title"]);
					$data[$key]['variant_name'] = addslashes($v["title"]);
					$data[$key]['is_open'] = 0;
					$data[$key]['sku'] = $v["sku"];
					$data[$key]['description'] =addslashes($value["body_html"]);
					$data[$key]['short_description'] = addslashes($value["body_html"]);
					$data[$key]['weight'] = $v["weight"];//单位 kg
					$data[$key]['price'] = $v["price"];
					$data[$key]['currency'] = $shoparr['shop']["currency"]; 
					//$data['special_price'] = $value["special_price"];
					//$data['meta_title'] = $value["meta_title"];
					//$data['meta_keywords'] = $value["meta_keywords"];
					$data[$key]['base_image'] = $imgsrc;
					$data[$key]['small_image'] = $imgsrc;
					$data[$key]['thumbnail_image'] = $imgsrc;
					//$data['including'] = trim($value["including"],",");
					//$data['fabric'] = trim($value["fabric"],",");
					$data[$key]['images'] = $img;
					//var_dump($data);
					//产品信息准备完毕准备导入
					//导入之前先判断是否已经有该产品，如果有的话则跳过该产品
					//$checksql="SELECT * FROM `db_magento_productlist` WHERE `webname`='{$webname}' AND `product_id` = '{$product_id}';";
					//$chrow = $this->db1->query($checksql)->result_array();
					//if(!empty($arr_row)) continue; //判断是否为空，如果不为空跳过
					//exit;
				}
               }
			   if(count($data)){
					$this->db1->insert_batch("shopify.db_magento_productlist",$data);
			   }

		 	}
		 	    
                
		    }
		       
		}

	}

	//获取订单
	public function getorder(){
		//获取全部shopify店铺
		$sql="SELECT * FROM `d_shop` WHERE `platfromname` = 'Shopify';";
		$arr_row = $this->db1->query($sql)->result_array();
		    //判断是否为空
	    if(!empty($arr_row)){
	      foreach ($arr_row as $value) {
	      	//var_export($value);
	      	if (empty($value["amazonkey"])) {
	      		continue;
	      	}
	        $amazonkey = json_decode($value["amazonkey"],true);
	              //判断是否存在shopid
	          if(isset($amazonkey['apptoken'])){
	          	if(isset($amazonkey['shopifytoken'])){
	          		//存在shopid执行orderlist
	              $this->orderlist($amazonkey['apptoken'],$amazonkey['shopifytoken'],$value['id']);
	                //回传物流单号
	              $this->returntracking_number($amazonkey['apptoken'],$amazonkey['shopifytoken'],$value['id']);
	              //退款
	              $this->refunds($amazonkey['apptoken'],$amazonkey['shopifytoken'],$value['id']);
	          	}
	          
	          //$this->returnlist($amazonkey['apptoken'],$value['id']);
	         }
	      }
	    }
	}

	//获取订单
	public function orderlist($token,$shop,$shopid){
		//获取所有open状态也就是开启状态的订单
		$query = array(
			"Content-type" => "application/json" // Tell Shopify that we're expecting a response in JSON format
		);
		//当前时间戳
		$timestamp=time();
		$create_time_from=$timestamp-15*24*3600;
		$create_time_from_date=date('Y-m-d',$create_time_from).'T'.date('H:i:s',$create_time_from);
		//选项，默认打开open状态的，具体参考文档
		$opt=array(
	    "created_at_min" => $create_time_from_date,
	    );
	    // Run API call to get all products
        $orders = $this-> shopify_call($token, $shop, "/admin/orders.json", $opt, 'GET');

        // Get response
		$products =json_decode($orders['response'],true);
		foreach ($products['orders'] as $value) {
	      //var_export($value);
		  $this->adderporder($shopid,$value);	
		}
		//var_export($products);
	}
    

    //把订单导入到系统中
    public function adderporder($shopid,$data){
    //第一步，判断该订单是否存在于erp中
    	 $ordersn=$data['name']; // #1002 类似于这样的
    	 $sql="select * from db_order_list where `tradeid` = '{$ordersn}' and `shopid` = '{$shopid}';";
    	 $isin=$this->db1->query($sql)->row_array();
    	 //判断
    	 if ($isin["order_id"]) return 0;
         //判断 订单是否是已支付状态的 financial_status == paid
         if($data['financial_status'] != 'paid' ) return 0;
            // var_export($data);
            // exit;
         //准备导入。
		    foreach ($data['line_items'] as $value) {
		      //赋值给sku
		      $sku=$value['sku'];
		     // var_export(addslashes(trim($value['sku'])));
		      //exit;
		      //判断查询是不是在sku表中，如果有不在的直接中断查询直接状态改为待审查
		      $check=$this->db1->get_where("db_goods","goods_sku='{$sku}'")->result_array();
		      if (empty($check)) {
		          $checklist=$this->db1->get_where("db_goods","cognatelist like '%,{$sku},%'")->result_array();
		          if(empty($checklist)){
		            $Status=7;
		            break;
		          }else{
		            $Status=2;
		          }
		      }else{
		         $Status=2;
		      }
		    }
            // var_export($Status);
            //exit;

		    $postdata="";
            $postdata["order_sn"] = $this->amazondata->getNo();
            $postdata["dates"] = date("Y-m-d");
            $postdata["order_status"] = $Status;
            $postdata["order_source"] ='正常订单';
            $postdata['shipping_status']=0;
            $postdata['ebay_orderID']=$data['id'];
            //顾客id
            $postdata["customerid"] = addslashes(trim($data['shipping_address']['name']));
            $postdata["email"] = $data['email'];
            //收件人信息
            $postdata["consignee"]=addslashes(trim($data['shipping_address']['name']));
            $postdata["country"] = ucfirst(strtolower(addslashes(trim($data['shipping_address']['country']))));
            $postdata["country_code"] = trim($data['shipping_address']['country_code']);
            if($data['shipping_address']['country']){
              $rscountry = $this->db1->get_where("d_country","countrynamecn='".$data['shipping_address']['country']."'or countryid = '".$data['shipping_address']['country']."' or countrynamede ='".$data['shipping_address']['country']."'")->result_array();
              if(isset($rscountry[0]["id"])){
                $postdata["country_cn"] = $rscountry[0]["countrynameen"];
                $postdata["country"] = ucfirst(strtolower($rscountry[0]['countrynamecn']));
				if($postdata["country_code"]=='')$postdata["country_code"]= $rscountry[0]["countryid"];

              }else{
                $postdata["country_cn"] ='';
              }
            }
            $postdata["province"] = $data['shipping_address']['province'];
            $postdata["city"] = $data['shipping_address']['city'];
            $postdata["address"] = $data['shipping_address']['address1'];
            $postdata["zipcode"] = $data['shipping_address']['zip'];
            $postdata["tel"] = $data['shipping_address']['phone'];
            $postdata["tradeid"] = $ordersn;
            //获取店铺信息
            $rshop = $this->db1->get_where("d_shop","id=".$shopid)->result_array();
            $postdata["shopname"] = $rshop[0]["name"];
            $postdata["shopoper"] = $rshop[0]["updateoper"];
            $postdata["shopid"] = $shopid;
            //订单金额信息
            $postdata["moneytype"] = $data['currency'];
            $exchange=$this->db1->get_where("d_moneyrate","name='{$data['currency']}'")->result_array();
            if ($exchange[0]["rate"]) {
            	$exchangerate = $exchange[0]["rate"];
            }else{
                $exchangerate=1;
            }
            //不包含运费
            $postdata["goods_originask"] = $data['subtotal_price'];
            $postdata["goods_amount"] = $postdata["goods_originask"] * $exchangerate;
            if(isset($data['shipping_lines'][0]['price']))
            	$shipping_lines_price = $data['shipping_lines'][0]['price'];
            else
            	$shipping_lines_price = 0;
            $postdata["shipping_originask"] = $shipping_lines_price;
            $postdata['shipping_fee'] = $postdata["shipping_originask"] * $exchangerate;
            $postdata["add_time"] = time();
            $postdata["ordertime"] = date("Y-m-d H:i:s",strtotime($data['created_at']));
            $postdata["saleschannel"] = 'shopify';
            $postdata["pay_fee"] = $data['total_price'] * 0.015 * $exchangerate;
            $postdata["platform_fee"] = $data['total_price'] * 0.1 * $exchangerate;
            //留言信息 //无留言信息
            $postdata["platform_message"]= '';
            //汇率
            $postdata['moneyrate']  = $exchangerate;
            $postdata['platformID']=$rshop[0]['platfrom'];
            //付款id 付款账户 暂时无法获取
            // $postdata["payid"]='';
            // $postdata["payaccount"]='';
            $this->db1->trans_begin();
            try{
				$this->db1->insert("db_order_list",$postdata);

				$orderID = $this->db1->insert_id();

				$factorycode =$this->amazondata->factorycode();
				$weight = 0;
				//循环出来产品sku和产品qty
				$skuarr=array();
				$buyer_product_qty=array();
                $pprice=array();
				foreach ($data['line_items'] as $value) {
					$skuarr[] = addslashes(trim($value['sku']));
					$buyer_product_qty[] = $value['quantity'];
                    $pprice[]=$value['price'];
				}
				$skui=0;
				$skunum=count($skuarr);
					foreach ($skuarr as $key =>$sku) {
						$sku=trim($sku);
						//var_export($sku);
					$rgoods = $this->db1->get_where("db_goods","goods_sku='".$sku."'")->result_array();
					//var_export($rgoods);
					if(isset($rgoods[0]["goods_id"]))
					{
						$goods_id = $rgoods[0]["goods_id"];
						$g_weights = $rgoods[0]["g_weight"]?$rgoods[0]["g_weight"]:400;
						$sweight = $buyer_product_qty[$skui]* $g_weights;
						$weight = $weight+$sweight;
						$costprice = 0;
						/*****************成本价计算方式********
						**  11、12开头定制的衣服按成本价计算
						**  批量的sku 按关联价计算
						**  外采购的衣服按成本价计算
						*********************************/
						if(is_numeric($sku) && preg_match('|^\d{8}$|',$sku))	//数字并且8位SKU并且11 12开头
						{
							$goodscode  = substr($sku,0,2);//取开头2位数
							if(in_array($goodscode,$factorycode))	//是否存在在工厂code
							{
								$costprice = $rgoods[0]["g_costprice"];	//定制衣服按成本价计算
							}
						}else{
							//如果当前SKU不是8位，查询父SKU是不是8位并且11，12开头
							if(is_numeric($rgoods[0]["goods_parent_sku"]) && preg_match('|^\d{8}$|',$rgoods[0]["goods_parent_sku"]))	//数字并且8位SKU并且11 12开头
							{
								$goodscodes  = substr($rgoods[0]["goods_parent_sku"],0,2);//取开头2位数
								if(in_array($goodscodes,$factorycode))	//是否存在在工厂code
								{
									$costprice = $rgoods[0]["bulkprice"];	//批量按关联价计算
								}
							}else{
								$costprice = $rgoods[0]["g_costprice"];
							}
						}
						



					}else{
						$goods_id = 0 ;
						$costprice = 0;
						$sweight=400;
					}
					$postsell = "";
					$postsell["order_id"] = $orderID;
					$postsell["goods_id"] = $goods_id;
					$postsell["goods_name"] = addslashes($rgoods[0]['goods_name']);
					$postsell["goods_sn"] =  $sku;
					$postsell["costprice"] =$costprice;
					$postsell["goods_number"] = $buyer_product_qty[$skui];
					$postsell["goods_price"] = $pprice[$skui]*$exchangerate;
					$postsell["goods_weight"]=$sweight;
					$postsell["goods_amount"] = $pprice[$skui]* $buyer_product_qty[$skui]*$exchangerate;
					$postsell["originsellprice"] = $pprice[$skui]?$pprice[$skui]:0;
					$postsell["originsku"] = $sku;
					$postsell["product_link"]='';
					//$postsell["sale_remark"]='';
					$this->db1->insert("db_order_sell",$postsell);

					if($goods_id==0)
					{
						$this->db1->update("db_order_list",array("order_status"=>7),"order_id=".$orderID);
					}
					if($weight)
					{
						$this->db1->update("db_order_list",array("orderweight"=>$weight),"order_id=".$orderID);
					}
					$skui++;
				 }
                //更新日志
				$imgdata["goods_id"] = $orderID;	//订单ID
				$imgdata["updatetime"] = date("Y-m-d H:i:s");
				$imgdata["createUid"] = 0;
				$imgdata["types"] = 3;
				$imgdata["content"] = 'shopify接口自动新增订单,交易ID='.$ordersn;
				$imgdata["createUser"] ='auto';
				$this->db1->query($this->db1->insert_string('db_goods_log', $imgdata));
				

				$this->db1->trans_commit();
			}catch (Exception $e){
				$this->db1->trans_rollback();
				$msg =  $e->getMessage();
				print_r($msg);exit;
			}
    }

    //物流单号回传
    public function returntracking_number($token,$shop,$shopid){
    	//根据店铺名称查找需要回传的订单
    	$listrow= $this->db1->get_where("db_order_list","shopid='{$shopid}' and is_update_platform='0' and (order_status='4' or order_status = '5' ) ")->result_array();
        foreach ($listrow as $value) {
        if($value['shipping_number']==null) continue;
        $id=$value['ebay_orderID'];
        $tradeid=$value['tradeid'];
        // $shippingrow=$this->db1->get_where("db_order_express","id='{$shipping_id}'")->result_array();
        // foreach ($shippingrow as $sv) {
        // 	//暂时设置为magento物流方式
        // 	$shipping_name=$sv['magento_express'];
        // }
        $shipping_number=$value['shipping_number'];
        // $shipping_name="DHL Express";

        //确定返回值类型
    	$query = array(
			"Content-type" => "application/json" // Tell Shopify that we're expecting a response in JSON format
		);
		//添加选项，添加物流信息
		//$line_itemsarr=array();
        //"line_items"=>array(array("id"=>'436641333291'))
		$opt=array(
			"fulfillment" => array(
	    "tracking_number" => $shipping_number,
	    "notify_customer" => true
	     )
	    );
	     //echo $id;
	     //var_export($opt);

	    // die;
	    // Run API call to get all products
        $orders = $this->shopify_call($token, $shop, "/admin/orders/{$id}/fulfillments.json", $opt, 'POST');
        //var_export($orders);
        //die;
        // Get response
		//$products =json_decode($orders['response'],true);

        //回执
		$sql="update `db_order_list` set `is_update_platform` = '1' where `shopid`='{$shopid}' and `tradeid` = '{$tradeid}';";
        $date=$this->db1->query($sql);
        }
    }

    public function refunds($token,$shop,$shopid){
    	//根据店铺id查找需要退款的订单
    	$listrow= $this->db1->get_where("db_paypal_refund","shop_id='{$shopid}' and `platfromname`='shopify' and refund_status='2' ")->result_array();
    	$linum=count($listrow);
    	if($linum<=0) return 0;
    	//表示有需要退款的款项
    	foreach ($listrow as $value) {
    		//创建退款
    		//确定返回值类型
	    	$query = array(
				"Content-type" => "application/json" // Tell Shopify that we're expecting a response in JSON format
			);
			//获取订单的order_id  ebay_orderID
			$order=$this->db1->get_where("db_order_list","order_id='{$value['order_id']}'")->result_array();
			$order_id=$order[0]['ebay_orderID'];
            //需要先获取订单交易信息 capture GET /admin/orders/#{order_id}/transactions.json
             $transactions = $this-> shopify_call($token, $shop, "/admin/orders/{$order_id}/transactions.json");

             $transactionsls = json_decode($transactions['response'],true);
			// var_dump($transactionsls);
			// return 0;
             //循环交易记录
             $parent_id=0;
             foreach ($transactionsls['transactions'] as  $v) {
             	if(($v['kind'] == 'capture' || $v['kind'] == 'sale' )&& $v['status'] == 'success'){
             		$parent_id=$v['id'];
             		$gateway=$v['gateway'];
             	}
             }

             // var_dump($transactionsls);
             // return 0;
            //如果parent_id = 0 说明无法退款 没有获取到交易信息
             if($parent_id === 0){
             	//填写回执
             	$sql="update `db_paypal_refund` set `refund_status` = '4',`paypal_fail`='parent_id无法找到，请核查订单' where `pay_id`='{$value['pay_id']}';";
                $this->db1->query($sql);
                continue;
             }

             //获取订单信息
        $orders = $this-> shopify_call($token, $shop, "/admin/orders/{$order_id}.json");

        // Get response
		$products =json_decode($orders['response'],true);
        //var_dump($products);
        $refund_line_items=array();
        foreach ($products['order']['line_items'] as $v) {
        	$refund_line_items[]=array(
                 'line_item_id'=>$v['id'],
                 'quantity'=>$v['quantity']
        		);
        }

       

			//创建选项
			$opt=array(
                  'refund'=>array(
                  	'restock' => true,
                  	'notify'=> true,
                  	"note" => '',
                  	//"shipping"=>array('amount'=>0),
                  	"refund_line_items"=>$refund_line_items,
                  	"transactions"=>array(
                  		 array(
                  		 'order_id'=>$order_id,
                         'parent_id'=>$parent_id,
                         'amount'=>$value['refund_money'],
                         'kind'=>'refund',
                         'gateway'=>$gateway,
                         )
                  		)
                  	)
				);
        if(isset($products['order']['refunds'][0]['refund_line_items']))
          if(count($products['order']['refunds'][0]['refund_line_items'])>0)
        	  unset($opt['refund']['refund_line_items']);

			// //Create a new refund for an order  POST /admin/orders/#{order_id}/refunds.json
			// $ref = $this->shopify_call($token, $shop, "/admin/orders/{$order_id}/refunds/calculate.json", $opt, 'POST');
			// //由于没有测试只是暂时先这样写，随后再2调整
   //          var_dump($ref['response']);
   //          $opt=json_decode($ref['response'],true);
   //          $opt['refund']['transactions'][0]['kind']='refund';

            //var_dump($opt);
            // $opt=json_encode($opt);
            $ref = $this->shopify_call($token, $shop, "/admin/orders/{$order_id}/refunds.json", $opt, 'POST',array("Content-Type: application/json"));
            //var_dump($ref['response']);
            // return 0;
			$refli=json_decode($ref['response'],true);
			//var_dump($refli);
			$sql="update `db_paypal_refund` set `refund_status` = '4',`paypal_fail`='未知原因，请联系管理员' where `pay_id`='{$value['pay_id']}';";
			if(isset($refli['refund']['transactions'])){
				$sql="update `db_paypal_refund` set `refund_status` = '4',`paypal_fail`='error_code:{$refli['refund']['transactions']['error_code']}' where `pay_id`='{$value['pay_id']}';";
				//如果状态为success的时候则认为退款成功
				if($refli['refund']['transactions'][0]['status']=='success'){
					$TIMESTAM=$refli['refund']['transactions']['created_at'];
					//GROSSREFUNDAMT 退还给对方的钱
					$GROSSREFUNDAMT=$refli['refund']['transactions']['amount'];
                $sql="update `db_paypal_refund` set `refund_status` = '3',`TIMESTAM`='{$TIMESTAM}',`GROSSREFUNDAMT`='{$GROSSREFUNDAMT}' where `pay_id`='{$value['pay_id']}';";
				}
			}
			//填写回执
			$this->db1->query($sql);
			
    	}
    	return 0;

    }

    //基础函数
    function shopify_call($token, $shop, $api_endpoint, $query = array(), $method = 'GET', $request_headers = array()) {
    
	// Build URL
	$url = "https://" . $shop . ".myshopify.com" . $api_endpoint;
	if (!is_null($query) && in_array($method, array('GET', 	'DELETE'))) $url = $url . "?" . http_build_query($query);
	// Configure cURL
	$curl = curl_init($url);
	curl_setopt($curl, CURLOPT_HEADER, TRUE);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
	curl_setopt($curl, CURLOPT_MAXREDIRS, 3);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	// curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 3);
	// curl_setopt($curl, CURLOPT_SSLVERSION, 3);
	curl_setopt($curl, CURLOPT_USERAGENT, 'My New Shopify App v.1');
	curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
	curl_setopt($curl, CURLOPT_TIMEOUT, 30);
	curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
	// Setup headers
	$request_headers[] = "";
	if (!is_null($token)) $request_headers[] = "X-Shopify-Access-Token: " . $token;
	curl_setopt($curl, CURLOPT_HTTPHEADER, $request_headers);
	if ($method != 'GET' && in_array($method, array('POST', 'PUT'))) {
		if (is_array($query)) {

			$fquery = http_build_query($query);
			if($request_headers[0]=='Content-Type: application/json')
			$fquery=json_encode($query);
		}
		
		curl_setopt ($curl, CURLOPT_POSTFIELDS, $fquery);
	}
    
	// Send request to Shopify and capture any errors
	$response = curl_exec($curl);
	$error_number = curl_errno($curl);
	$error_message = curl_error($curl);
	// Close cURL to be nice
	curl_close($curl);
	// Return an error is cURL has a problem
	if ($error_number) {
		return $error_message;
	} else {
		// No error, return Shopify's response by parsing out the body and the headers
		$response = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
		// Convert headers into an array
		$headers = array();
		$header_data = explode("\n",$response[0]);
		$headers['status'] = $header_data[0]; // Does not contain a key, have to explicitly set
		array_shift($header_data); // Remove status, we've already set it above
		foreach($header_data as $part) {
			$h = explode(":", $part);
			$headers[trim($h[0])] = trim($h[1]);
		}
		// Return headers and Shopify's response
		return array('headers' => $headers, 'response' => $response[1]);
	}
    
}



}



?>